/*
 See LICENSE folder for this sample’s licensing information.

 Abstract:
 A single line in the graph.
 */

import SwiftUI

struct GraphCapsule: View {
  var index: Int
  var height: CGFloat
  var range: Range<Double>
  var overallRange: Range<Double>

  var heightRatio: CGFloat {
    max(CGFloat(magnitude(of: range) / magnitude(of: overallRange)), 0.15)
  }

  var offsetRatio: CGFloat {
    CGFloat((range.lowerBound - overallRange.lowerBound) / magnitude(of: overallRange))
  }

  // 波浪动画//其实就是延迟动画.delay根据index*时间系数延迟动画
  var rippling: Animation {
    Animation.spring(dampingFraction: 0.5)
      .speed(2)
      .delay(0.03 * Double(index))
  }

  struct AnimationTrigger: Equatable {
    let heightRatio: CGFloat
    let offsetRatio: CGFloat
  }

  var animationTrigger: some Equatable {
    AnimationTrigger(heightRatio: heightRatio, offsetRatio: offsetRatio)
  }

  var body: some View {
    Capsule()
      .fill(Color.white)
      .frame(height: height * heightRatio, alignment: .bottom)
      .offset(x: 0, y: height * -offsetRatio)
      //      .animation(rippling) //此API即将废弃 使用如下替换
      // 动画根据value执行
      .animation(rippling, value: animationTrigger)
  }
}

struct GraphCapsule_Previews: PreviewProvider {
  static var previews: some View {
    GraphCapsule(index: 0, height: 150, range: 10 ..< 50, overallRange: 0 ..< 100)
  }
}
